<template>
  <div class="sys-page scrollBar">
    <!--   区域配置   -->
    <!--
      管理人员仅可见区域设置里面的7.更改建筑排序
      维修人员仅可见区域设置里面的8.一键巡检
      -->
    <div style="height: 600px" v-if="userInfo.role == 0">
      <div class="lamp-btn">更改建筑排序</div>
      <div class="area-box" style="height: calc(100% - 60px)">
        <div v-for="(item,idx) in areaList" @click="showSortCard(item,idx)">{{ item.name }}</div>
      </div>
    </div>
    <div style="height: 600px" v-if="userInfo.role == 2">
      <div class="lamp-btn">一键巡检功能</div>
      <div class="tips-box">
        <div class="tips" :class="value ? 'red' : 'green'"
             v-for="(value,key) in checkMsg"
             style="margin-bottom: 10px">{{key}}-{{value ? '正在巡检': '未巡检'}}
<!--          <img src="@/assets/images/icon-succ.png" v-if="value" />-->
<!--          <img src="@/assets/images/icon-error.png" v-else />-->
        </div>
      </div>
      <div class="area-box">
        <div v-for="(item,idx) in areaList"
             :class="{'on': areaIdx == idx}"
             @click="changeArea(item,idx)">
          {{ item.name }}
        </div>
      </div>
      <div class="cancel-btn xj-btn" @click="onSiteInspection">开始巡检</div>
    </div>
    <div class="line"></div>
    <div style="display: flex; justify-content: space-between">
      <el-select v-model="gatewayVal" placeholder="请选择网关" style="width: 200px">
        <el-option :label="item.gatewayName" :value="item.gatewayId" v-for="item in gatewayList" />
      </el-select>
      <div class="cancel-btn xj-btn" style="margin-top: 0;" @click="gatewayInspectionHandle">开始网关巡检</div>
    </div>
    <div class="line" style="margin-top: 20px"></div>
    <div class="cancel-btn xj-btn" style="margin-bottom: 30px" @click="controlHandle">强制自动控制</div>



    <!--  弹窗  -->
    <sort-card ref="sortCard" :lampData="lampData" />
    <el-dialog
        v-model="diaVisible"
        title="巡检进度"
        :close-on-click-modal="false"
        :append-to-body="true"
        width="967px"
        @close="closeForm"
    >
      <el-progress
          :text-inside="true"
          :stroke-width="24"
          :percentage="percentage"
          status="success"
      />

      <template #footer>
        <div class="dialog-footer">
          <div @click="resetForm" class="cancel-btn xj-btn" style="margin-right: 0">中断巡检</div>
        </div>
      </template>
    </el-dialog>
    <!--  强制控制  -->
    <el-dialog
        v-model="controlVisible"
        title="强制自动控制"
        :close-on-click-modal="false"
        :append-to-body="true"
        width="967px"
        @close="controlVisible = false"
    >
      <el-radio-group v-model="controlRadio">
        <el-radio :value="item" v-for="item in controlList">{{ item }}</el-radio>
      </el-radio-group>
      <template #footer>
        <div class="dialog-footer">
          <div @click="controlAgainVisible = true" class="sure-btn" style="margin-right: 10px">确认</div>
          <div @click="controlVisible = false" class="cancel-btn">取消</div>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="controlAgainVisible"
        title="提示"
        :close-on-click-modal="false"
        :append-to-body="true"
        width="967px"
        @close="controlAgainVisible = false"
    >
      <div>是否执行{{controlRadio}}操作?</div>
      <template #footer>
        <div class="dialog-footer">
          <div @click="submitControlAgainForm" class="sure-btn" style="margin-right: 10px">确认</div>
          <div @click="controlAgainVisible = false" class="cancel-btn">取消</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import {
  lampCheck,
  judgeLightOnline,getAllGatewayList,CheckByGateway,
  refreshGatewayData, getAutoCheckFlag, TowerZongLan, BrigeZongLan,
  checkGetProgress, stopCheck, getEnforceAutoFlag,setEnforceAutoFlag
} from "../../router/api.js";
import {mapGetters} from "vuex";
import SortCard from "./modules/sortCard.vue";

export default {
  name: "regionConfiguration",
  components: {SortCard},
  computed: {
    ...mapGetters(['currentNav','userInfo','refreshFlag'])
  },
  data() {
    return {
      areaIdx: -1,
      areaList: [
        { name: '一区', value: 1 },
        { name: '二区', value: 2 },
        { name: '散货', value: 3 },
      ],
      checkMsg: {},
      flag: true,
      timer: null,
      fetchingFlag: true,
      lampData: [],
      gatewayList: [],
      gatewayVal: '',
      diaVisible: false,
      percentage: 0,
      controlVisible: false,
      controlRadio: '',
      controlList: ['开启自动控制', '关闭自动控制', '取消'],
      controlAgainVisible: false,
      timerCheck: false,
    }
  },
  watch:{
    'currentNav': {
      deep: true,
      handler(n){
        console.log(n)
      }
    },
    'refreshFlag': {
      deep: true,
      handler(n) {
        if(n) {
          refreshGatewayData();
          // judgeLightOnline();

          this.$store.commit('SET_WAIT', true)
        }
      }
    }
  },
  /*beforeRouteLeave(to, from, next) {
    clearInterval(this.timer);
    this.timer = null;
    this.fetchingFlag = false;

    next();
  },*/
  unmounted() {
    clearInterval(this.timer);
    this.timer = null;
    this.fetchingFlag = false;

    clearInterval(this.timerCheck);
    this.timerCheck = null;
  },
  created() {
    this.getAutoCheckFlagHandle();
    this.getAllGatewayListHandle();

    this.timer = setInterval(() => {
      if(this.fetchingFlag){
        this.getAutoCheckFlagHandle();
      }
    }, 1000 * 5)
  },
  methods: {
    showSortCard(item,idx){
      this.getLampData(idx);
    },
    async getLampData(idx) {
      let resLamp = await TowerZongLan();
      let resLampBridge = await BrigeZongLan()
      let lighthouse = [], lampBridge = [];
      if (resLamp.data.code == 200) {
        lighthouse = JSON.parse(JSON.stringify(resLamp.data.data)).filter(opt => opt.towerArea == idx+1);
      }else{
        this.$message.warning('无法请求服务器资源，请确认服务器是否开启')
      }
      if (resLampBridge.data.code == 200) {
        lampBridge = JSON.parse(JSON.stringify(resLampBridge.data.data)).filter(opt => opt.brigeArea == idx+1);
      }

      this.lampData = [...lighthouse,...lampBridge];
      this.lampData.sort((a,b) => a.locationUi - b.locationUi)
      /*this.lampData = [...lighthouse];
      if (this.lampData.length >= 3) {
        this.lampData.splice(3, 0, ...lampBridge)
      } else {
        this.lampData.push(...lampBridge)
      }*/

      this.$refs.sortCard.show()
    },
    changeArea(item,idx){
      this.areaIdx = idx;
    },
    async getAutoCheckFlagHandle(){
      this.fetchingFlag = true;
      let res = await getAutoCheckFlag();
      if(res.data.code == 200){
        this.checkMsg = res.data.data;
      }
    },
    async onSiteInspection(){
      let res = await lampCheck({area: this.areaIdx+1});

      if (res.data.code != 200) {
        this.$message.warning(res.data.msg)
      }
      await this.getAutoCheckFlagHandle();
    },
    async getAllGatewayListHandle(){
      let res = await getAllGatewayList();
      if(res.data.code == 200){
        this.gatewayList = res.data.data;
      }
    },
    async gatewayInspectionHandle(){
      if(!this.gatewayVal){
        this.$message.warning('请选择网关');
        return;
      }
      let res = await CheckByGateway({
        gatewayId: this.gatewayVal
      });
      if(res.data.code == 200){
        this.$message.success(res.data.data)
      }

      await this.checkGetProgressHandle();
    },
    async checkGetProgressHandle(){
      this.diaVisible = true;
      let resp = await checkGetProgress({
        gatewayId: this.gatewayVal
      });
      if(resp.data.code == 200){
        this.percentage = resp.data.data;
      }

      this.timerCheck = setInterval(async () => {
        let resp = await checkGetProgress({
          gatewayId: this.gatewayVal
        });
        if(resp.data.code == 200){
          this.percentage = resp.data.data;
        }else{
          this.diaVisible = false;
          clearInterval(this.timerCheck);
          this.timerCheck = null;
        }
      },3000)
    },
    closeForm(){
      this.percentage = 0;
      this.diaVisible = false;
      clearInterval(this.timerCheck);
      this.timerCheck = null;
    },
    async resetForm(){
      let res = await stopCheck({gatewayId: this.gatewayVal});
      if(res.data.code == 200){
        // this.diaVisible = false;
        // clearInterval(this.timerCheck);
        // this.timerCheck = null;

        this.closeForm();
        this.$message.success(res.data.data)
      }
    },
    async controlHandle(){
      this.controlVisible = true;
      let res = await getEnforceAutoFlag();
      if(res.data.code == 200){
        this.controlRadio = res.data.data
      }
    },
    async submitControlAgainForm(){
      let res = await setEnforceAutoFlag({ enforceAutoFlagString : this.controlRadio });
      if(res.data.code == 200){
        this.$message.success(res.data.msg)
        this.controlAgainVisible = false;
        this.controlVisible = false;
      }else{
        this.$message.warning(res.data.msg)
      }
    },

  }
}
</script>

<style scop lang="scss">
.sys-page {
  margin-left: 10px;
  height: 100%;
  overflow: auto;

  .xj-btn{
    float: right;
    margin-top: 30px;
    margin-right: 80px;

    &:before{
      content: '';
      width: 0;
      display: inline-block;
    }
  }

  .lamp-btn{
    width: 206px;
    height: 46px;
    line-height: 46px;
    color: #336666;
    font-size: 18px;
    background: url("@/assets/images/title-bg.png") no-repeat left top;
    background-size: 100% 100%;
    margin-bottom: 20px;
    text-align: center;
  }

  .area-box{
    display: flex;
    align-items: center;
    justify-content: center;
    div{
      width: 200px;
      height: 60px;
      text-align: center;
      line-height: 60px;
      border: 1px solid #D0D9DE;
      color: #336666;
      font-size: 16px;
      font-weight: 400;
      background-color: #E2E6EC;
      margin-right: 20px;
      cursor: pointer;

      &:last-child{
        margin-right: 0;
      }

      &.on{
        background-color: #3CBDFF;
        border-color: #3CBDFF;
      }
    }
  }

  .tips-box{
    .tips{
      height: 100px;
      line-height: 100px;
      font-size: 18px;
      font-weight: 700;
      text-align: center;
    }

    .red{
      color: #f8446b;
      background-color: #E7C7CD;
      border: 1px solid #E6A2B1;
    }
    .green{
      color: #15C666;
      background-color: #D0F4E0;
      border: 1px solid #76DEA6;
    }
  }

  .line{
    background-color: #366;
    height: 1px;
    width: 100%;
    margin-bottom: 20px;
  }
}

</style>
